package com.price.custom

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.drawable.Drawable
import android.graphics.drawable.NinePatchDrawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import com.price.common.extend.logError
import com.price.core.R
import kotlin.math.max
import kotlin.math.min

/**
 * @ClassName: RoundImageView
 * @Description: 图像圆形化
 * 圆形ImageView，可设置最多两个宽度不同且颜色不同的圆形边框。
 * 设置颜色在xml布局文件中由自定义属性配置参数指定
 */
class RoundImageView : AppCompatImageView {
    //边框的宽度
    private var mBorderThickness = 0
    private var mContext: Context
    private val defaultColor = Color.WHITE

    private var mBorderColor = 0

    // 控件默认长、宽
    private var defaultWidth = 0
    private var defaultHeight = 0

    constructor(context: Context) : super(context) {
        mContext = context
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        mContext = context
        setCustomAttributes(attrs)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        mContext = context
        setCustomAttributes(attrs)
    }

    private fun setCustomAttributes(attrs: AttributeSet?) {
        val a = mContext.obtainStyledAttributes(attrs, R.styleable.roundImageview)
        mBorderThickness = a.getDimensionPixelSize(R.styleable.roundImageview_border_width, 0)
        mBorderColor =
            a.getColor(R.styleable.roundImageview_border_color, defaultColor)
    }

    override fun onDraw(canvas: Canvas) {
        val drawable = drawable ?: return
        if (width == 0 || height == 0) {
            return
        }

        if (drawable.javaClass == NinePatchDrawable::class.java) return
        val bitmap = drawableToBitmap(drawable)
        if (defaultWidth == 0) {
            defaultWidth = width
        }
        if (defaultHeight == 0) {
            defaultHeight = height
        }


        val radius = min(defaultWidth, defaultHeight) / 2
        val roundBitmap = getCroppedRoundBitmap(bitmap, radius)
        canvas.drawBitmap(
            roundBitmap,
            0f,
            0f,
            null
        )
        val halfWidth=(mBorderThickness+0.5f)/2f
        if (mBorderThickness != 0) {
            drawCircleBorder(canvas, halfWidth, mBorderColor)
        }
    }

    private fun drawableToBitmap(drawable: Drawable): Bitmap {
        val bitmap = Bitmap.createBitmap(
            drawable.intrinsicWidth, drawable.intrinsicHeight,
            if (drawable.opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565
        )
        val canvas = Canvas(bitmap)
        drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
        drawable.draw(canvas)
        return bitmap
    }

    /**
     *
     * 获取裁剪后的圆形图片
     */
    private fun getCroppedRoundBitmap(bmp: Bitmap, radius: Int): Bitmap {
        var scaledSrcBmp: Bitmap?
        val diameter = radius * 2
        // 为了防止宽高不相等，造成圆形图片变形，因此截取长方形中处于中间位置最大的正方形图片
        val bmpWidth = bmp.width
        val bmpHeight = bmp.height
        var squareWidth = 0
        var squareHeight = 0
        var x = 0
        var y = 0
        var squareBitmap: Bitmap?
        if (bmpHeight > bmpWidth) { // 高大于宽
            squareHeight = bmpWidth
            squareWidth = squareHeight
            x = 0
            y = (bmpHeight - bmpWidth) / 2
            // 截取正方形图片
            squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth, squareHeight)
        } else if (bmpHeight < bmpWidth) { // 宽大于高
            squareHeight = bmpHeight
            squareWidth = squareHeight
            x = (bmpWidth - bmpHeight) / 2
            y = 0
            squareBitmap = Bitmap.createBitmap(bmp, x, y, squareWidth, squareHeight)
        } else {
            squareBitmap = bmp
        }
        scaledSrcBmp = if (squareBitmap.width != diameter || squareBitmap.height != diameter) {
            Bitmap.createScaledBitmap(squareBitmap, diameter, diameter, true)
        } else {
            squareBitmap
        }
        val output =
            Bitmap.createBitmap(scaledSrcBmp.width, scaledSrcBmp.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)
        val paint = Paint()
        val rect = Rect(0, 0, scaledSrcBmp.width, scaledSrcBmp.height)
        paint.isAntiAlias = true
        paint.isFilterBitmap = true
        paint.isDither = true
        canvas.drawARGB(0, 0, 0, 0)
        canvas.drawCircle(
            (scaledSrcBmp.width / 2).toFloat(),
            (scaledSrcBmp.height / 2).toFloat(),
            (scaledSrcBmp.width / 2).toFloat(),
            paint
        )
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawBitmap(scaledSrcBmp, rect, rect, paint)
        squareBitmap = null
        scaledSrcBmp = null
        return output
    }

    /**
     * 边缘画圆
     */
    private fun drawCircleBorder(canvas: Canvas, halfWidth: Float, color: Int) {
        val paint = Paint()
        /* 去锯齿 */paint.isAntiAlias = true
        paint.isFilterBitmap = true
        paint.isDither = true
        paint.color = color
        /* 设置paint的　style　为STROKE：空心 */
        paint.style = Paint.Style.STROKE
        /* 设置paint的外框宽度 */
        paint.strokeWidth = mBorderThickness.toFloat()
        canvas.drawArc(
            halfWidth,
            halfWidth,
            defaultWidth.toFloat() - halfWidth,
            defaultHeight.toFloat() - halfWidth,
            0f,
            360f,
            false,
            paint
        )
    }
}
